<template>
    <div class="doctor-inquiry" v-loading="isLoading" element-loading-text="加载中" element-loading-background="rgba(255,255,255,.7)">
        <div class="l-panel inquiry-top-box">
            <div class="head-photo">
                <el-image :src="doctorInfo.doctorheadimg"></el-image>
            </div>
            <div>
                <p>
                    <img src="@/assets/img/icon_doctor.png" alt="">
                    {{doctorInfo.doctorname}}
                    <el-popover placement="right" width="500" trigger="hover" v-model="visible" @show="creatQrCode">
                        <img class="code-size" :src="qrCodeUrl" alt="">
                        <div style="text-align: center; margin: 0">
                            <el-button type="primary" size="mini" @click="saveCode">下载二维码</el-button>
                        </div>
                        <img class="icon-img" slot="reference" src="@/assets/img/icon_code.png" alt="">
                    </el-popover>
                </p>
                <div class="inquiry-doctor-info">
                    <div class="l-flex-1">
                        <p><span>职称：</span>{{doctorInfo.doctorjobtitle}}</p>
                        <p><span>科室：</span>{{doctorInfo.departmentname}}</p>
                    </div>
                    <div class="l-flex-1">
                        <p><span>医院：</span>{{doctorInfo.doctorworkaddress || 0}}</p>
                        <p><span>家庭医生患者：</span>{{doctorInfo.isConcernCounts || 0}}</p>
                    </div>
                </div>
            </div>
            <div>
                <div>
                    <p>{{doctorInfo.interrogationnum | numFormat}}</p>
                    <p>我的接诊量</p>
                </div>
                <div>
                    <p>{{doctorInfo.prescriptionnum | numFormat}}</p>
                    <p>我的处方</p>
                </div>
            </div>
            <div class="btn-frame">
                <p class="btn-tips" v-if="socketMsg.length > 0">您上次接诊方式为<span style="color: #409EFF;">{{doctorMsg.inquiryType == 1?'视频接诊':doctorMsg.inquiryType == 3? '图文+视频接诊':doctorMsg.inquiryType == 2 ? '图文接诊':'无'}}</span></p>
                <p class="btn-tips">若要更换其他接诊方式，需要回到此页面重新选择。</p>
                <!-- <el-button type="primary" @click="gotoInquiry">网络接诊</el-button> -->
                <div class="l-flex l-flex-wrap">
                    <el-button class="btn-size" type="primary" :loading="loading" @click="gotoInquiry(2)">图文接诊</el-button>
                    <el-button class="btn-size" type="primary" :loading="loading" @click="gotoInquiry(1)">视频接诊</el-button>
                    <el-button class="btn-size" type="primary" :loading="loading" @click="gotoInquiry(3)">图文+视频接诊</el-button>
                    <!-- 非暖禾，展示自主开方 -->
                    <el-button v-if="$global.isAuto" class="btn-size" type="success" plain :loading="loading" @click="gotoSubstitute">自主开方</el-button>
                    <el-button v-if="$global.isEntity" class="btn-size" type="primary" plain :loading="loading" @click="gotoInterface">远程会诊</el-button>
                </div>
            </div>
        </div>
        <div class="l-panel">
            <div class="statistical-head">
                <div class="statistical-name">
                    <div>数量统计｜<span>历史问诊处方记录</span></div>
                </div>
                <div class="statistical-bottom">
                    <div class="statistical-number">
                        <p>问诊数量：<span>{{interrogationNumber || 0}}</span></p>
                        <p>处方数量：<span>{{prescriptionNumber || 0}}</span></p>
                    </div>
                    <div class="statistical-tab">
                        <ul>
                            <p>周期：</p>
                            <li :class="activeValue == item.value ? 'active' : ''" v-for="(item, index) in tabList" :key="index" @click="statisticalTab(item.value)">{{item.lable}}</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="statistical-chart">
                <div id="main" ref="myEchart" style="width: 100%;height:400px;"></div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                doctorInfo: {},
                tabList: [{
                        lable: '近7天',
                        value: '1'
                    },
                    {
                        lable: '近30天',
                        value: '2'
                    },
                    {
                        lable: '近半年',
                        value: '3'
                    }
                ],
                activeValue: '1',
                dateList: [],
                interrogationList: [],
                prescriptionList: [],
                interrogationNumber: 0,
                prescriptionNumber: 0,
                isLoading: false,
                socketMsg: {},
                socketLineUp: {},
                doctorMsg: {},
                doctorPackage: [],
                visible: false,
                qrCodeUrl: '',
                loading: false,
                myEchart: null,
            }
        },
        mounted() {
            // setTimeout(() => {
            this.getDoctorOnlieConsultainfo();
            this.queryHistoryInterrogation();
            this.getDoctorMsg();
            // }, 500)

            /* --- test: 增加41关闭socket连接事件 --- */
            // this.$setWs.send(41, {
            //     // logId: -1,
            //     packageType: 41,
            // });
        },
        computed: {
            //在computed方法声明并存储到vuex
            getWsMsg() {
                return this.$store.state.webSocketMsg;
            },
        },
        watch: {
            getWsMsg(data, val) {
                console.log('===【getWsMsg】===', data, val)
                if (data != 'pong' && data != '') {
                    if (data.packageType == 6) { //获取患者排队事件
                        console.log(data, '------------------获取患者排队事件-------------------')
                        this.socketMsg = data.list
                    }
                    if (data.packageType == 7) { //获取患者加入房间事件
                        console.log(data, '------------------获取患者加入房间事件-------------------')
                        this.socketLineUp = data
                    }
                }
            },
        },
        methods: {
            getDoctorOnlieConsultainfo() {
                this.isLoading = true
                this.$ajax.getDoctorOnlieConsultainfo({ webToken: this.$authInfo.webToken() }).then(res => {
                    this.doctorInfo = res.data || {};
                    this.isLoading = false;
                    // console.log(this.doctorInfo)
                }).catch(err => {
                    this.isLoading = false
                    this.$util.message(err.msg, 'error')
                });
            },
            getDoctorMsg() { //医生详情
                this.loading = true;
                this.$ajax.getInquiryDoctorInfo({ webToken: this.$authInfo.webToken(), id: this.$authInfo.getUser().id }).then(res => {
                    this.loading = false;
                    this.doctorMsg = res.data || {};
                    this.doctorPackage = res.data.doctorPackageInfoResps || [];
                }).catch(err => {
                    this.loading = false;
                    this.$util.message(err.msg, 'error')
                });
            },
            // 统计数据
            queryHistoryInterrogation() {
                let params = {
                    webToken: this.$authInfo.webToken(),
                    statisticscode: this.activeValue
                }
                this.$ajax.queryHistoryInterrogation(params).then(res => {
                    let { code, data } = res;
                    if (code == 1 && data) {
                        this.dateList = [];
                        this.interrogationList = [];
                        this.prescriptionList = [];
                        for (let i = data.interrogation.length - 1; i >= 0; i--) {
                            if (params.statisticscode === '2') {
                                this.dateList.push('近' + data.interrogation[i].datatime + '周');
                                // this.dateList.reverse();
                            } else {
                                this.dateList.push(data.interrogation[i].datatime);
                            }
                            this.interrogationList.push(data.interrogation[i].number);
                            this.prescriptionList.push(data.prescription[i].number);
                        }
                        this.interrogationNumber = res.data.intcount;
                        this.prescriptionNumber = res.data.prescount;
                        this.$nextTick(() => {
                            this.myEcharts();
                        })
                    }
                }).catch(err => {
                    console.log(err)
                    this.$util.message(err.msg, 'error')
                });
            },
            // 柱状图图tabbar
            statisticalTab(value) {
                this.activeValue = value
                this.queryHistoryInterrogation()
            },
            // 统计图
            myEcharts() {
                if (!this.$refs.myEchart) return;

                if (this.myEchart != null && this.myEchart != "" && this.myEchart != undefined) {
                    this.myEchart.dispose(); //销毁
                }

                // 指定图表的配置项和数据
                var option = {
                    // title: {
                    //     text: 'ECharts 入门示例'
                    // },
                    tooltip: {},
                    // legend: {
                    //     data:['销量']
                    // },
                    xAxis: {
                        data: this.dateList
                    },
                    yAxis: {
                        minInterval: 1,
                    },
                    series: [{
                            name: '问诊数量',
                            type: 'bar',
                            barWidth: '15%',
                            data: this.interrogationList,
                            itemStyle: {
                                normal: {
                                    barBorderRadius: [6, 6, 0, 0], // 设置柱状图圆角
                                    color: '#3AA1FF'
                                },
                            }
                        },
                        {
                            name: '处方数量',
                            type: 'bar',
                            barWidth: '15%',
                            background: 'red',
                            data: this.prescriptionList,
                            itemStyle: {
                                normal: {
                                    barBorderRadius: [6, 6, 0, 0], // 设置柱状图圆角
                                    color: '#4ECB73'
                                }
                            }
                        }
                    ]
                };

                this.myEchart = null;

                // 基于准备好的dom，初始化echarts实例
                this.myEchart = this.$echarts.init(this.$refs.myEchart);
                this.myEchart.clear();
                this.myEchart.resize();

                // 使用刚指定的配置项和数据显示图表。
                this.myEchart.setOption(option);
            },
            gotoInquiry(type) { //跳转至网络接诊
                if (type == 1 && this.doctorPackage[0].enable == 0) {
                    this.$util.message('暂未开启此服务，请联系管理员', 'error')
                } else if (type == 2 && this.doctorPackage[1].enable == 0 && this.doctorPackage[2].enable == 0 && this.doctorPackage[3].enable == 0) {
                    this.$util.message('暂未开启此服务，请联系管理员', 'error')
                } else if (type == 3 && ((this.doctorPackage[1].enable == 0 && this.doctorPackage[2].enable == 0 && this.doctorPackage[3].enable == 0) || this.doctorPackage[0].enable == 0)) {
                    this.$util.message('暂未开启此服务，请联系管理员', 'error')
                } else {
                    if (this.socketMsg.length > 0 && this.doctorMsg.inquiryType != type) {
                        this.$confirm(`您确定要切换为<strong style="color: #409EFF;">${ type == 1 ? '视频接诊' : type == 3 ? '视频+图文接诊' : '图文接诊'}</strong>吗? 切换后可能导致已排队候诊的患者无法发起问诊。请谨慎操作。`, '提示', {
                            customClass: 'l-confirm',
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            dangerouslyUseHTMLString: true,
                            closeOnClickModal: false,
                            closeOnPressEscapes: false,
                            showClose: false,
                        }).then(() => {
                            let para = {
                                working: 1,
                                inquiryType: type,
                            }
                            this.$ajax.receivePatients(para).then(res => {
                                let data = {
                                    id: JSON.parse(this.$getStore('adminUserInfo')).id, //医生id
                                    packageType: 29,
                                }
                                this.$setWs.send(29, data);
                                this.$router.push('/video');
                                this.$removeStore('inquiryType')
                                window.sessionStorage.removeItem('inquiryType');
                            }).catch(err => {

                            })
                        }).catch(() => {

                        })
                    } else {
                        let para = {
                            working: 1,
                            inquiryType: type,
                        }
                        this.$ajax.receivePatients(para).then(res => {
                            let data = {
                                id: JSON.parse(this.$getStore('adminUserInfo')).id, //医生id
                                packageType: 29,
                            }
                            this.$setWs.send(29, data);
                            this.$router.push('/video');
                            this.$removeStore('inquiryType')
                            window.sessionStorage.removeItem('inquiryType');
                        }).catch(err => {

                        })
                    }
                }
            },
            creatQrCode() { //生成二维码
                let params = {
                    doctorId: this.$authInfo.getUser().id,
                    path: `pages/user_side/index/index_doctorlist/index_doctor_details/index_doctor_details?doctorId=${this.$authInfo.getUser().id}`,
                }
                // this.codeLoading = true
                this.$ajax.getQRCode(params).then(res => {
                    // this.codeLoading = false;
                    this.qrCodeUrl = res.data.data
                }).catch(err => {
                    // this.codeLoading = false;
                    this.$util.message(err.msg, 'error')
                });
            },
            downloadIamge(imgsrc, name) { //下载图片地址和图片名
                var image = new Image();
                // 解决跨域 Canvas 污染问题
                image.setAttribute("crossOrigin", "anonymous");
                image.onload = function() {
                    var canvas = document.createElement("canvas");
                    canvas.width = image.width;
                    canvas.height = image.height;
                    var context = canvas.getContext("2d");
                    context.drawImage(image, 0, 0, image.width, image.height);
                    var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

                    var a = document.createElement("a"); // 生成一个a元素
                    var event = new MouseEvent("click"); // 创建一个单击事件
                    a.download = name || "photo"; // 设置图片名称
                    a.href = url; // 将生成的URL设置为a.href属性
                    a.dispatchEvent(event); // 触发a的单击事件
                };
                image.src = imgsrc;
            },
            saveCode() { // 保存二维码
                this.downloadIamge(this.qrCodeUrl, this.doctorInfo.doctorname)
            },
            gotoSubstitute() {
                this.$router.push('/prescription');
            },
            gotoInterface() {
              this.$router.push({
                path: "/remoteConsult/myConsult?activeName=remoteConsult",
              });
            }
        }
    }
</script>

<style lang="scss">
    .doctor-inquiry {
        .l-panel {
            width: 100%;
            padding: 10px 30px;
        }

        .btn-frame {
            width: 330px;
            // display: flex;
            // flex-direction: column;
            padding-left: 12px;

            .btn-size {
                width: 48%;
                margin: 12px 1%;
            }

            .btn-tips {
                // max-width: 125px;
            }
        }

        .inquiry-top-box {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;

            .head-photo {
                width: 128px;
                height: 180px;
                margin-right: 6px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .icon-img {
                margin-left: 5px;
                height: 22px !important;
                width: 22px !important;
            }

            > div {
                &:nth-child(2) {
                    color: #3c3c3c;
                    width: 35%;

                    > p {
                        font-size: 22px;
                        margin-bottom: 10px;

                        img {
                            width: 20px;
                            height: 22px;
                            vertical-align: middle;
                            display: inline-block;
                            margin-right: 32px;
                        }
                    }
                }

                &:nth-child(3) {
                    background: #f8fafd;
                    height: 220px;
                    display: flex;
                    width: 30%;
                    align-items: center;
                    justify-content: space-around;
                    border-radius: 10px;

                    > div {
                        text-align: center;

                        > p {
                            font-size: 14px;
                            color: #3c3c3c;

                            &:first-child {
                                color: #e53b46;
                                font-size: 36px;
                                margin-bottom: 20px;
                            }
                        }
                    }
                }
            }

            .inquiry-doctor-info {
                display: flex;
                justify-content: space-between;
                font-size: 14px;
                padding: 0 5px 0 0;

                p {
                    margin-bottom: 30px;
                }

                span {
                    color: #757575;
                }
            }
        }

        .statistical-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 16px;
            color: #3c3c3c;

            .statistical-name {

                // margin-right: 300px;
                span {
                    color: #757575;
                    font-size: 14px;
                }
            }

            .statistical-bottom {
                display: flex;
                align-items: center;
            }

            .statistical-number {
                margin-right: 80px;

                p {
                    display: inline-block;

                    span {
                        color: #e53b46;
                        margin-left: 10px;
                    }

                    &::before {
                        content: "";
                        display: inline-block;
                        border-radius: 50%;
                        width: 10px;
                        height: 10px;
                        background: #3aa1ff;
                        margin-right: 3px;
                    }

                    &:last-child {
                        padding-left: 50px;

                        &::before {
                            background: #4ecb73;
                        }
                    }
                }
            }

            .statistical-tab {
                ul {
                    display: flex;
                    align-items: center;

                    li {
                        margin-left: 40px;
                        cursor: pointer;
                        padding: 5px 10px;
                    }
                }

                .active {
                    color: #fff;
                    background: #006db8;
                    padding: 5px 10px;
                    border-radius: 16px;
                }
            }
        }
    }
</style>
